//
//  PeiXunViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-26.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "PeiXunViewController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#import "CityShowViewController.h"
#import "PXBaoViewController.h"
#import "MainTabBarController.h"
#define CityTag 35

@interface PeiXunViewController ()

@end

@implementation PeiXunViewController

- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _BttArr = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onChangeProResponse:)
                                                     name:NotProChg
                                                   object:nil];
    }
    return self;
}

-(void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_TopCityBtt release];
    [_BttArr release];
    [_ScrollView release];
    [_NavBtt release];
    [_BMBtt release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
  
    m_titleBttBarItem = [[MainTabBarController setTitle:@"培训机构"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _BMBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_BMBtt setImage:[UIImage imageNamed:@"button_right.png"] forState:UIControlStateNormal];
    _BMBtt.frame =CGRectMake(320-55, 7, 50, 30);
    [_BMBtt addTarget:self action:@selector(baomingBtt) forControlEvents:UIControlEventTouchUpInside];
    [_BMBtt retain];
    UILabel* tBMLab = [[UILabel alloc] initWithFrame:CGRectMake(3, 5, 40, 20)];
    [tBMLab setBackgroundColor:[UIColor clearColor]];
    [tBMLab setTextColor:[UIColor whiteColor]];
    tBMLab.textAlignment =UITextAlignmentCenter;
    tBMLab.tag =60;
    [tBMLab setText:@"报名"];
    [tBMLab setFont:[UIFont systemFontOfSize:13]];
    [_BMBtt addSubview:tBMLab];
    [tBMLab release];
    
    
    _ScrollView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44) style:UITableViewStylePlain];
    _ScrollView.delegate  =self;
    _ScrollView.dataSource = self;
    [self.view addSubview:_ScrollView];
    
    //城市切换
     _TopCityBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_TopCityBtt addTarget:self action:@selector(ChangeCity) forControlEvents:UIControlEventTouchUpInside];
    _TopCityBtt.frame =CGRectMake(210, 0, 60, 44);
    [_TopCityBtt retain];
    
    UILabel* tCityLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 12, 40, 20)];
    [tCityLab setBackgroundColor:[UIColor clearColor]];
    [tCityLab setFont:[UIFont systemFontOfSize:13]];
    tCityLab.tag = CityTag;
    [tCityLab setTextColor:[UIColor whiteColor]];
    [_TopCityBtt addSubview:tCityLab];
    [tCityLab release];
    
    UIImageView* tDownTrImg = [[UIImageView alloc] initWithFrame:CGRectMake(30, 20, 10, 5)];
    tDownTrImg.transform =CGAffineTransformMakeRotation(M_PI);
    [tDownTrImg setImage:[UIImage imageNamed:@"arrow.png"]];
    [_TopCityBtt addSubview:tDownTrImg];
    [tDownTrImg release];
    
    [self setCityLab];
    _NowPage =1;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getFirmList&province_id=%@&page=1&pageSize=100",RequestCurrentURL,tAppDel.m_Province_id];
    [self requestListData:tURLStr];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:_BMBtt];
    [self.navigationController.navigationBar addSubview:_TopCityBtt];
      [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [_BMBtt removeFromSuperview];
    [_TopCityBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onChangeProResponse:(NSNotification *)notification
{
    [self setCityLab];
    _NowPage =1;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getFirmList&province_id=%@&page=1&pageSize=100",RequestCurrentURL,tAppDel.m_Province_id];
    [self requestListData:tURLStr];
}
-(void) setCityLab
{
    UILabel* tCityLab = (UILabel*)[_TopCityBtt viewWithTag:CityTag];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* tEnumCityStr = nil;
    for (NSDictionary* tCityDic in tAppDel.m_CityDataArr) {
        tEnumCityStr = [NSString stringWithFormat:@"%d",[[tCityDic objectForKey:@"id"] intValue]];
        if ([tEnumCityStr isEqualToString:tAppDel.m_Province_id]) {
            [tCityLab setText:[tCityDic objectForKey:@"name"]];
            return;
        }
    }
    
}

-(void) ChangeCity
{
    CityShowViewController* tCityVC = [[CityShowViewController alloc] init];
    tCityVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tCityVC animated:YES];
    [tCityVC release];
}

//报名
-(void) baomingBtt
{
    NSMutableString* tMutStr = [NSMutableString string];
    int i=0,j=0;
    for (NSArray* tInArr in _BttArr) {
        for (UIButton* tBtt in tInArr) {
            if (tBtt.tag < 0) {
                NSDictionary* tSecDic = [_DataListArr objectAtIndex:i];
                NSArray* tSecArr = [tSecDic objectForKey:@"classes"];
                NSDictionary* tRowDic = [tSecArr objectAtIndex:j];
                [tMutStr appendFormat:@"%d",[[tRowDic objectForKey:@"id"] intValue]];
                [tMutStr appendString:@","];
            }
            j++;
        }
        i++;
    }
    
    if ([tMutStr length] > 0) {
        [tMutStr deleteCharactersInRange:NSMakeRange([tMutStr length]-1, 1)];
        PXBaoViewController* tPXBaoVC = [[PXBaoViewController alloc] init];
        tPXBaoVC.m_BaoIDs =tMutStr;
        tPXBaoVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tPXBaoVC animated:YES];
        [tPXBaoVC release];
    }else{
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"请选择培训班" detailText:@"" isCue:-1 delayTime:2];
    }
}
//选择或者取消
-(void) choiceBttPressed:(UIButton*)f_sender
{
    if (f_sender.tag > 0) {
        //开始选中
        [f_sender setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
    }else{
        [f_sender setImage:[UIImage imageNamed:@"select.png"] forState:UIControlStateNormal];
    }
    f_sender.tag =-f_sender.tag;
    int tChoiceNum = 0;
    for (NSArray* tInArr in _BttArr) {
        for (UIButton* tBtt in tInArr) {
            if (tBtt.tag < 0) {
                tChoiceNum ++;
            }
        }
    }
    UILabel* tBMLab =(UILabel*)[_BMBtt viewWithTag:60];
    if (tChoiceNum <= 0) {
        [tBMLab setText:[NSString stringWithFormat:@"报名"]];
    }else{
        [tBMLab setText:[NSString stringWithFormat:@"报名%d",tChoiceNum]];
    }
    
    
}

#pragma mark-
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* tSectionView = [[UIView alloc] initWithFrame:CGRectMake(-1, -1, 322, 35)];
    [tSectionView setBackgroundColor:[UIColor colorWithRed:230/255.f green:230/255.f blue:230/255.f alpha:1]];
    NSDictionary* tSecDic = [_DataListArr objectAtIndex:section];
    UILabel* tNameLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 8, 200, 18)];
    [tNameLab setBackgroundColor:[UIColor clearColor]];
    [tNameLab setText:[tSecDic objectForKey:@"name"]];
    [tNameLab setFont:[UIFont systemFontOfSize:15]];
    [tSectionView addSubview:tNameLab];
    [tNameLab release];
    return [tSectionView autorelease];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}
#pragma mark-
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_DataListArr count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary* tSecDic = [_DataListArr objectAtIndex:section];
    return [[tSecDic objectForKey:@"classes"] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* tCell= nil;
    int tRow = indexPath.row;
    int tSection = indexPath.section;
    static NSString* s_CellStr = @"kcell";
    tCell = [tableView dequeueReusableCellWithIdentifier:s_CellStr];
    if (tCell  == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:s_CellStr] autorelease];
        tCell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIColor* tLineColor =[UIColor colorWithRed:206/255.f green:206/255.f blue:206/255.f alpha:1];
        CALayer* tLine0 = [CALayer layer];
        tLine0.frame =CGRectMake(0, 30, 320, 1);
        [tLine0 setBackgroundColor:tLineColor.CGColor];
        [tCell.layer addSublayer:tLine0];
        
        CALayer* tLine1 = [CALayer layer];
        tLine1.frame =CGRectMake(0, 60, 320, 1);
        [tLine1 setBackgroundColor:tLineColor.CGColor];
        [tCell.layer addSublayer:tLine1];
        
        CALayer* tLine2 = [CALayer layer];
        tLine2.frame =CGRectMake(0, 90, 320, 1);
        [tLine2 setBackgroundColor:tLineColor.CGColor];
        [tCell.layer addSublayer:tLine2];
        
        CALayer* tLine3 = [CALayer layer];
        tLine3.frame =CGRectMake(160, 30, 1, 60);
        [tLine3 setBackgroundColor:tLineColor.CGColor];
        [tCell.layer addSublayer:tLine3];
        
        UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(12, 5, 320,20)];
        [tTitleLab setBackgroundColor:[UIColor clearColor]];
        [tTitleLab setFont:[UIFont systemFontOfSize:15]];
        tTitleLab.tag =50;
        [tCell addSubview:tTitleLab];
        [tTitleLab release];
        
        for (int i=0; i<4; i++) {
            UILabel* tDesLab = [[UILabel alloc] initWithFrame:CGRectMake(12+(i%2)*154, 35+i/2*30, 140,20)];
            [tDesLab setBackgroundColor:[UIColor clearColor]];
            [tDesLab setFont:[UIFont systemFontOfSize:12]];
            tDesLab.tag =51+i;
            [tCell addSubview:tDesLab];
            [tDesLab release];
        }
        UILabel* tPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(12, 95, 200,20)];
        [tPriceLab setBackgroundColor:[UIColor clearColor]];
        [tPriceLab setFont:[UIFont systemFontOfSize:12]];
        [tPriceLab setTextColor:[UIColor colorWithRed:251/255.f green:156/255.f blue:21/255.f alpha:1]];
        tPriceLab.tag =55;
        [tCell addSubview:tPriceLab];
        [tPriceLab release];
        
        UILabel* tWordLab = [[UILabel alloc] initWithFrame:CGRectMake(252, 95, 200,20)];
        [tWordLab setBackgroundColor:[UIColor clearColor]];
        [tWordLab setFont:[UIFont systemFontOfSize:12]];
        [tWordLab setText:@"选择"];
        tWordLab.tag =56;
        [tCell addSubview:tWordLab];
        [tWordLab release];

    }
    [tCell setBackgroundColor:[UIColor colorWithRed:245/255.f green:245/255.f blue:245/255.f alpha:1]];
    [tCell.contentView setBackgroundColor:[UIColor colorWithRed:245/255.f green:245/255.f blue:245/255.f alpha:1]];
    
    for (id tSubObject in tCell.subviews) {
        if ([tSubObject isKindOfClass:[UIImageView class]]||
            [tSubObject isKindOfClass:[UIButton class]]) {
            [tSubObject removeFromSuperview];
        }
    }
    [tCell addSubview:[[_BttArr objectAtIndex:tSection] objectAtIndex:tRow]];
    UILabel* tTitleLab = (UILabel*)[tCell viewWithTag:50];
    UILabel* tDesLab0 = (UILabel*)[tCell viewWithTag:51];
    UILabel* tDesLab1 = (UILabel*)[tCell viewWithTag:52];
    UILabel* tDesLab2 = (UILabel*)[tCell viewWithTag:53];
    UILabel* tDesLab3 = (UILabel*)[tCell viewWithTag:54];
    UILabel* tDesLab4 = (UILabel*)[tCell viewWithTag:55];
    NSDictionary* tSecDic = [_DataListArr objectAtIndex:tSection];
    NSDictionary* tRowDic = [[tSecDic objectForKey:@"classes"] objectAtIndex:tRow];
    [tTitleLab setText:[tRowDic objectForKey:@"name"]];
    [tDesLab0 setText:[NSString stringWithFormat:@"学时：%@",[tRowDic objectForKey:@"time"]]];
    [tDesLab1 setText:[NSString stringWithFormat:@"%@",[tRowDic objectForKey:@"address"]]];
    [tDesLab2 setText:[NSString stringWithFormat:@"教师：%@",[tRowDic objectForKey:@"teacher"]]];
    [tDesLab3 setText:[NSString stringWithFormat:@"开课时间：%@",[tRowDic objectForKey:@"start"]]];
    [tDesLab4 setText:[NSString stringWithFormat:@"费用："]];
    return tCell;
}


#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}


-(void) requestListData:(NSString*)f_URLStr
{
    [self addHudLoad];
    _NowPage++;
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:f_URLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestListFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestListFinish:)];
    [tRequestPage startAsynchronous];
}

-(void) requestListFail:(ASIHTTPRequest*)request
{
    _NowPage--;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestListFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            [_DataListArr release];
            _DataListArr = nil;
            _DataListArr =[tRealDataDic objectForKey:@"list"];
            [_DataListArr retain];
            [_BttArr removeAllObjects];
            UIImage* tNoneImg = [UIImage imageNamed:@"select.png"];
            for (int i=0; i<[_DataListArr count]; i++) {
                NSMutableArray* tInArr = [NSMutableArray array];
                [_BttArr addObject:tInArr];
                NSArray* tSrcInArr = [[_DataListArr objectAtIndex:i] objectForKey:@"classes"];
                for (int j=0; j<[tSrcInArr count]; j++) {
                    UIButton* tBtt = [UIButton buttonWithType:UIButtonTypeCustom];
                    [tBtt addTarget:self action:@selector(choiceBttPressed:) forControlEvents:UIControlEventTouchUpInside];
                    tBtt.tag =1000*(i+1)+j;
                    tBtt.frame =CGRectMake(285, 95, 20, 20);
                    [tBtt setImage:tNoneImg forState:UIControlStateNormal];
                    [tInArr addObject:tBtt];
                }
            }
            
            [_ScrollView reloadData];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:NO delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}
@end
